package ee.siimoliver.chat.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

public class ApplicationProperties extends Properties {

	private static final long serialVersionUID = 1L;
	public static String PROPERTIES_FILE = Const.PROPERTIES_FILE; //default properties file
	
    private ApplicationProperties() {
    	loadProperties();
    }

    private static class SingletonHolder { 
            public static final ApplicationProperties instance = new ApplicationProperties();
    }

    public static ApplicationProperties getInstance() {
            return SingletonHolder.instance;
    }
    
    private void makeNewFileAndPopulate() {
    	File file = new File(PROPERTIES_FILE);
    	try {
			PrintWriter pw = new PrintWriter(file);
			for (String line : Const.PROPERTIES_FILE_CONTENT) {
				pw.println(line);
			}
			pw.close();
		} catch (FileNotFoundException e) {}
    }
    
	public boolean loadProperties() {
		while (true) {
			try {
				BufferedReader bfr = new BufferedReader(new FileReader(PROPERTIES_FILE));
				load(bfr);
				bfr.close();
				return true;
			} catch (FileNotFoundException fnf) {
				makeNewFileAndPopulate();
			} catch (IOException e) {
				System.err.println("Error loading application properties file");
				return false;
			}
		}
	}
	
	public void storeProperties() throws IOException {
		try {
			PrintWriter pw = new PrintWriter(new FileWriter(PROPERTIES_FILE));
			store(pw, " User properties");
			pw.close();
		} catch (IOException e) {
			throw new IOException("Error storing application properties file");
		}
	}
}
